<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/4
 * Time: 18:16
 */

namespace App\Logic;

use App\Model\FriendModel;
use App\Model\UserModel;
use App\Services\HelpService;
use EasySwoole\ORM\DbManager;
use App\Model\FriendApplyModel;
class FriendLogic
{
    function exameApply($id,$userId,$status){
        try{
            $friendApply = FriendApplyModel::create()->where(['id' => $id, 'user_id' => $userId])->get();
            if (empty($friendApply)) {
                return ['error' => 1, 'msg' => '记录不存在'];
            }

            if ($friendApply['status'] != 0) {
                return ['error' => 1, 'msg' => '审核失败'];
            }

            $unionid = HelpService::createUnionId($userId);
            //开启事务
            $friendApply->update(['status' => $status]);
           if($status==1){
               FriendModel::create([
                   'user_id' => $userId,
                   'unionid' => $unionid,
                   'friend_user_id' => $friendApply['applier_user_id'],
                   'created_at' => HelpService::msectimeToStr(HelpService::msectime()),
                   'updated_at' =>HelpService::msectimeToStr(HelpService::msectime()),
               ])->save();

               FriendModel::create([
                   'user_id' => $friendApply['applier_user_id'],
                   'unionid' => $unionid,
                   'friend_user_id' => $userId,
                   'created_at' => HelpService::msectimeToStr(HelpService::msectime()),
                   'updated_at' => HelpService::msectimeToStr(HelpService::msectime()),
               ])->save();
           }
        } catch(\Throwable  $e){
            //回滚事务
            DbManager::getInstance()->rollback();
            return ['error' => 1, 'msg' => '记录不存在'];
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
                 return ['error' =>0, 'msg' => '操作成功'];
        }
}